Sending Emails with Attachments Using SendGrid in Python
A step-by-step implementation of sending an email with attachments using SendGrid in Python.
Step 1: Import the necessary modules
We begin by importing the required modules for our implementation:
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.classes import Mail
from sendgrid.helpers.mail import Attachment, FileContent, FileName, FileType, Disposition
Step 2: Define the send_email function
Next, we define the send_email
function, which takes parameters for the sender’s email, recipient’s email, subject, plain text content, HTML content, and attachments (optional):
def send_email(sender_email, recipient_email, subject, plain_content, html_content, attachments=None):
message = Mail(
from_email=sender_email,
to_emails=recipient_email,
subject=subject,
plain_text_content=plain_content,
html_content=html_content)
Step 3: Handle attachments (if provided)
If attachments are provided, we iterate over each attachment file and create a SendGrid Attachment
object for it. We read the file contents, set the file name, type, and disposition as necessary:
if attachments:
for attachment in attachments:
with open(attachment, 'rb') as file:
attachment_data = file.read()
attachment_file = Attachment(
FileContent(attachment_data),
FileName(os.path.basename(attachment)),
FileType('application/octet-stream'),
Disposition('attachment')
)
message.attachment = attachment_file
Step 4: Send the email
We proceed to send the email using the SendGrid API. We instantiate the SendGridAPIClient
with the API key, then send the message:
try:
sg = SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))
response = sg.send(message)
print("Email sent successfully.")
return True
except Exception as e:
print("Error sending email:", str(e))
return False
Full Implementation below
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.classes import Mail
from sendgrid.helpers.mail import Attachment, FileContent, FileName, FileType, Disposition
def send_email(sender_email, recipient_email, subject, plain_content, html_content, attachment_paths=None):
# Create a Mail object
message = Mail(
from_email=sender_email,
to_emails=recipient_email,
subject=subject,
plain_text_content=plain_content,
html_content=html_content)
if attachment_paths:
# Iterate over attachment paths and add attachments to the email
for attachment_path in attachment_paths:
with open(attachment_path, 'rb') as file:
attachment_data = file.read()
attachment_file = Attachment(
FileContent(attachment_data),
FileName(os.path.basename(attachment_path)),
FileType('application/octet-stream'),
Disposition('attachment')
)
message.attachment = attachment_file
try:
# Send the email using the SendGrid API
sg = SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))
response = sg.send(message)
print("Email sent successfully.")
return True
except Exception as e:
print("Error sending email:", str(e))
return False
Step 5: Call the function with desired parameters
Finally, we call the send_email
function, passing the appropriate values for the sender’s email, recipient’s email, subject, plain content, HTML content, and attachments (if any):
plain_text = "This is the plain text content of the email."
html_content = "<h1>This is the HTML content of the email.</h1><p>It can include <strong>formatted text</strong> and other HTML elements.</p>"
attachments = ['path/to/file1.pdf', 'path/to/file2.jpg']
send_email("sender@example.com", "recipient@example.com", "Hello", plain_text, html_content, attachments)
That’s it! With these steps, you can send an email with attachments using SendGrid in Python. Feel free to customize the function and parameters according to your specific requirements.
Arjun is a Full-stack developer, who is fond of the web. Lives in Chikmagalur, Karnataka, India